﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Reader.Data;
using G.Navigate;
using System.IO.IsolatedStorage;
using G.Reader.API;

namespace G.Reader.View
{
    public partial class BookPage : GBasePage
    {

        #region 属性
        //private string[] bookParagraphs;
        ///// <summary>
        ///// 书本所有的段落
        ///// </summary>
        //public string[] BookParagraphs
        //{
        //    get
        //    {
        //        return bookParagraphs;
        //    }
        //    set
        //    {
        //        if (!object.ReferenceEquals(bookParagraphs, value))
        //        {
        //            bookParagraphs = value;
        //            this.NotifyPropertyChanged("BookParagraphs");
        //        }
        //    }
        //}
        #endregion

        public BookPage()
        {
            InitializeComponent();
            this.DataContext = this;
            list.LayoutUpdated += list_LayoutUpdated;
        }
        #region 书本初始化以及保存阅读状态
        BookInfo book;
        void list_LayoutUpdated(object sender, EventArgs e)
        {
            if (ScrollViewer == null)
                ScrollViewer = this.list.GetVisualChildren<ScrollViewer>().FirstOrDefault();
            if (ScrollViewer != null && list.ItemsSource != null)
            {
                PropertyValueChangedNotify.Create("VerticalOffset", ScrollViewer).PropertyValueChanged += new PropertyValueChangedHandle(BookPage_ScrollView_PropertyValueChanged);
                ScrollViewer.ScrollToVerticalOffset(book.ScrollHeight);
                list.LayoutUpdated -= list_LayoutUpdated;
            }
        }
        ScrollViewer ScrollViewer;
        private double currentReadProgress;
        void BookPage_ScrollView_PropertyValueChanged(DependencyObject d, PropertyValueChangedEventArgs e)
        {
            currentReadProgress = ScrollViewer.VerticalOffset * 100 / ScrollViewer.ExtentHeight;
            this.txtStatus.Text = string.Format("当前阅读进度：{0:N2}%", currentReadProgress);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (book == null)
            {
                //this.progress.IsIndeterminate = true;
                this.RegisterLoading("正在加载...");
                int id = int.Parse(this.NavigationContext.QueryString["bookid"]);
                book = GloabalData.Instance.BookDataBase.BookTable.FirstOrDefault(a => a.ID == id);
                System.Threading.ThreadPool.QueueUserWorkItem(LoadBook);
            }
        }
        private void LoadBook(object state)
        {
            var data = GloabalData.Instance.BookDataBase.ReadBook(book);
            this.Dispatcher.BeginInvoke(() =>
            {
                //this.BookParagraphs = data;
                list.ItemsSource = data;
                this.UnregisterLoading();
                //progress.IsIndeterminate = false;
            });

        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            if (fileUtil != null)
                fileUtil.Cancel();
            ScrollViewer sc = this.list.GetVisualChildren<ScrollViewer>().FirstOrDefault();
            if (sc.VerticalOffset == 0 || this.list.ItemsSource == null)
                return;
            book.ScrollHeight = sc.VerticalOffset;
            GloabalData.Instance.BookDataBase.SubmitChanges();
        }
        #endregion


        #region 语音朗读
        //Sounds.BingTranslator.LanguageServiceClient languageServiceClient;
        //private void btnPrevious_Click(object sender, EventArgs e)
        //{
        //    if (languageServiceClient == null)
        //    {
        //        languageServiceClient = new Sounds.BingTranslator.LanguageServiceClient();
        //        languageServiceClient.SpeakCompleted += new EventHandler<Sounds.BingTranslator.SpeakCompletedEventArgs>(languageServiceClient_SpeakCompleted);
        //    }
        //    //languageServiceClient.
        //    if (list.SelectedItem != null)
        //    {
        //        languageServiceClient.SpeakAsync(GloabalData.BingAPPID, list.SelectedItem as string, "zh-cn", "audio/wav");
        //    }
        //    else
        //    {
        //        MessageBox.Show("请选择一段文字开始朗读");
        //    }
        //}
        //WebClient client;
        //void languageServiceClient_SpeakCompleted(object sender, Sounds.BingTranslator.SpeakCompletedEventArgs e)
        //{
        //    if (client == null)
        //    {
        //        client = new WebClient();
        //        client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
        //    }
        //    client.OpenReadAsync(new Uri(e.Result));
        //    //media.Source = new Uri(e.Result);
        //}

        //void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        //{
        //    BookAudio bookaudio = new BookAudio();
        //    bookaudio.BookId = this.book.ID;
        //    bookaudio.ParagraphIndex = list.SelectedIndex;
        //    GloabalData.Instance.BookDataBase.AddBookAudio(e.Result, bookaudio);
        //    GetWav();
        //}

        //private void btnNext_Click(object sender, EventArgs e)
        //{
        //    List<AutioTrackTemp> aList = new List<AutioTrackTemp>();
        //    foreach (var item in GloabalData.Instance.BookDataBase.BookAudiosTable.Where(c => c.BookId == this.book.ID))
        //    {
        //        aList.Add(new AutioTrackTemp(item.BookPath, string.Format("{0}_{1}", this.book.BookName, item.ParagraphIndex), "G.Reader", this.book.BookName));
        //    }
        //    G.AudioPlaybackAgent.AudioPlayer.SetPlayList(aList);
        //    Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.Instance.Play();

        //}

        void AudioPlayer_GetList(object sender, EventArgs e)
        {

        }

        //private void media_MediaEnded(object sender, RoutedEventArgs e)
        //{
        //    GetWav();
        //}

        //private void GetWav()
        //{
        //    list.SelectedIndex++;
        //    string str = list.SelectedItem as string;
        //    if (!string.IsNullOrEmpty(str))
        //        languageServiceClient.SpeakAsync(GloabalData.BingAPPID, list.SelectedItem as string, "zh-cn", "audio/wav");
        //    else
        //        GetWav();
        //}

        #endregion

        #region 设置
        private void menuSetting_Click(object sender, EventArgs e)
        {

        }
        #endregion
        FileUtil fileUtil;
        private void Slider_FontSize_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Slider s = sender as Slider;
            this.Resources["textFontSize"] = s.Value;
        }

        #region 转码
        private void menuEncoding_Click(object sender, EventArgs e)
        {
            //Utils.PageOperateUtils.ValidatIsLogin((isok) =>
            //{
            //    if (isok)
            //    {
            if (MessageBox.Show("确定要进行编码转换吗？如果文本已经经过utf-8编码,那么无需再次编码，否则反而会出现乱码。", "提示", MessageBoxButton.OK) == MessageBoxResult.OK)
            {
                switch (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType)
                {
                    case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Wireless80211:
                    case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
                        break;
                    default:
                        if (MessageBox.Show("我们检查到您当前使用的网络不是wifi，如果仍然继续将会产生较大的流量费用，是否继续转码？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                        {
                            return;
                        }
                        break;
                }
                //if(Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType== Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Wireless80211
                fileUtil = new FileUtil();
                fileUtil.ChangeEncodingComplete += new ChangedEncodingCompleteHandel(fileUtil_ChangeEncodingComplete);
                fileUtil.ChangeEncodingProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(fileUtil_ChangeEncodingProgressChanged);
                fileUtil.Error += new EventHandler(fileUtil_Error);
                stackPanel_progress.Visibility = System.Windows.Visibility.Visible;
                fileProgressbar.Value = 0;
                txtProgress.Text = "正在进行转码...";
                fileUtil.ChangeEncoding(GloabalData.Instance.BookDataBase.GetBookStream(book));
            }
            //    }
            //});
        }

        void fileUtil_Error(object sender, EventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                stackPanel_progress.Visibility = System.Windows.Visibility.Collapsed;
                MessageBox.Show("转码过程中遇到错误，已经停止转码");
            });

        }

        void fileUtil_ChangeEncodingProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                fileProgressbar.Value = e.ProgressPercentage;
            });
        }

        void fileUtil_ChangeEncodingComplete(object sender, ChangedEncodingCompleteArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.RegisterLoading("正在加载...");
                stackPanel_progress.Visibility = System.Windows.Visibility.Collapsed;
                GloabalData.Instance.BookDataBase.UpdateBookWithStream(e.ChangedEncodingStream, book);
                ScrollViewer.ScrollToVerticalOffset(0);
                System.Threading.ThreadPool.QueueUserWorkItem(LoadBook);
            });

        }
        #endregion

        protected override void OnNavigatingBackFrom(NavigateBackFromEventArgs e)
        {
            base.OnNavigatingBackFrom(e);
            if (e.From == typeof(View.Book.ChooseReadProgressPage))
            {
                double d = double.Parse(e.Param as string);
                ScrollViewer.ScrollToVerticalOffset(d * ScrollViewer.ExtentHeight / 100);
            }
        }

        private void menuProgress_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(string.Format("/View/Book/ChooseReadProgressPage.xaml?progress={0:N2}", currentReadProgress));
        }

        private void btnCancle_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnPinToStart_Click(object sender, EventArgs e)
        {
            Uri uri = new Uri("/View/BookPage.xaml?bookid=" + book.ID, UriKind.Relative);
            if (Microsoft.Phone.Shell.ShellTile.ActiveTiles.FirstOrDefault(c => c.NavigationUri == uri) == null)
            {
                Microsoft.Phone.Shell.StandardTileData std = new Microsoft.Phone.Shell.StandardTileData();
                std.Title = book.BookName;
                Microsoft.Phone.Shell.ShellTile.Create(uri, std);
            }
            else
            {
                MessageBox.Show("已经添加到桌面了");
            }
        }

        private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (list.SelectedItem != null)
            {
                list.SelectedItem = null;
            }
        }
    }
}